package com.white.controller;

import com.white.service.CommunicateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * webSocket后端
 */
@ServerEndpoint(value = "/webSocket")
@Component
public class WebSocketController {

    @Autowired
    CommunicateService communicateService;

    /**
     * 浏览器数，需要互斥访问
     */
    private static final CopyOnWriteArrayList<WebSocketController> WEB_SOCKETS = new CopyOnWriteArrayList<>();
    private Session session;

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        WEB_SOCKETS.add(this);
    }


    @OnClose
    public void onClose() {
        WEB_SOCKETS.remove(this);
    }

    @OnMessage
    public void onMessage(String message) {
        /*广播消息*/
        WEB_SOCKETS.forEach((webSocketController -> webSocketController.sendMessage(message)));
    }

    @OnError
    public void onError(Throwable throwable) {
        throwable.printStackTrace();
    }

    /**
     * 发送消息
     * @param message
     */
    private void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
